package com.tyut.musicdreamer.service.gateway.filter;

import cn.dev33.satoken.SaManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Token参数处理过滤器
 * 处理URL参数中的token，将其转换为请求头
 */
@Component
@Slf4j
public class TokenParamFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 获取token名称
        String tokenName = SaManager.getConfig().getTokenName();
        
        // 从URL参数中获取token
        String token = request.getQueryParams().getFirst(tokenName);
        
        // 如果URL参数中有token，但请求头中没有，则添加到请求头
        if (token != null && !token.isEmpty()) {
            // 构建新的请求，添加token到请求头
            ServerHttpRequest.Builder requestBuilder = request.mutate();
            
            // 添加token到请求头，不添加前缀
            requestBuilder.header("Authorization", token);
            requestBuilder.header(tokenName, token);
            log.debug("从URL参数中获取token并添加到请求头: {}", token);
            
            // 使用新的请求对象继续处理
            return chain.filter(exchange.mutate().request(requestBuilder.build()).build());
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 在HeaderCleanupFilter之后执行
        return -150;
    }
} 